package queues

import (
	"context"
	"encoding/json"
	"fmt"
	"sweetsunnyflower/app/models/notify"
	"sweetsunnyflower/pkg/queue"
	"sweetsunnyflower/pkg/websocket"
	"time"

	"github.com/hibiken/asynq"
	"github.com/spf13/cast"
)

type RegisterPayload struct {
	UserID uint64
}

const Register = "register"

func RegisgerEvent(ID uint64) {
	payload := RegisterPayload{
		UserID: ID,
	}

	p, _ := json.Marshal(payload)

	queue.NewQueue().Run(asynq.NewTask(Register, p), 10, time.Second*0)

}

func HandleRegisterTask(ctx context.Context, t *asynq.Task) error {
	var p RegisterPayload
	if err := json.Unmarshal(t.Payload(), &p); err != nil {
		return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry)
	}

	content := &notify.Content{
		Title:   "注册成功",
		Message: "恭喜你,注册成功啦!现在实名认证,通过后送您100积分",
		Target:  "/users/certification",
	}

	c, err := content.Marshal()

	if err != nil {
		return fmt.Errorf("content.Marshal failed: %v", err)
	}

	notifyModel := notify.Notify{
		UserID:  p.UserID,
		Type:    notify.Certification,
		Status:  1,
		Content: string(c),
	}

	notifyModel.Create()

	websocketClient := websocket.NewClientManager()

	payload, _ := json.Marshal(notifyModel)

	con := websocket.ResponseContent{
		Action:  "register",
		Payload: string(payload),
	}

	cc, _ := json.Marshal(con)

	if client, ok := websocketClient.ClientMap[cast.ToString(p.UserID)]; ok {
		client.SendTo(client, string(cc), websocket.TextMessage, true)
	}

	return nil
}
